<template>
    <div class="rigth">
        <el-scrollbar style="flex: 1;" height="100%" v-loading="loading">
            <div class="container" @click="showDrawer(index)" v-for="item, index in  dataList" :key="item.id">
     
                <el-icon class="ico">
                    <Flag />
                </el-icon>
                <div class="text">
                    <el-badge :is-dot="data.index==2&&!item.readStatus" class="item">   <div>{{ item.title }}</div></el-badge>
                 
                    <div>
                        {{ item.content }}
                    </div>
                </div>
                <div class="function">
                    <div class="delete" v-if="data.index==1" @click.stop="deletes(item.id)">删除</div>
        
                    <div class="time"> {{ time(new Date(item.sendTime), false) }}</div>
                </div>
            </div>

        </el-scrollbar>
        <div class="pagin">
            <el-pagination class="pagination" background layout="prev, pager, next" @current-change="currentChange"
                :total="pageCount * 10" />

        </div>
    </div>
    <teleport to="body">
        <el-drawer v-model="drawer2" @close="data.setRelease()" :direction="direction">
            <template #header>
                <h4>{{ data.release ? '发布通知' : data.index == 2 ? '查看通知' : '修改通知' }}</h4>
            </template>
            <template #default>
                <div class="drawerContainer">
                    <div class="users">
                     
                        <img class="image"
                            :src="dataList[showIndex]?.sendUserImageUrl ? dataList[showIndex]?.sendUserImageUrl : store.user.imageUrl"
                            alt="">
                        <div>
                            <div>{{
                                dataList[showIndex]?.sendUserName ? dataList[showIndex]?.sendUserName : store.user.name
                            }}
                            </div>
                            <div v-if="!data.release">{{ time(new Date(dataList[showIndex]?.sendTime)) }}</div>
                        </div>
                    </div>
                    <!-- 标题 -->
                    <el-form style="flex: 1; display: flex;flex-direction: column;" :model="form" label-position="right"
                        ref="ruleFormRef" :rules="rules">
                        <el-form-item prop="input">
                            <el-input v-if="data.release||data.index != 2" maxlength="255" v-model="form.input" type="text"
                                style="margin-bottom: 1vh;" placeholder="标题，不能少于1，大于255字" />
                        </el-form-item>


                        <div class="tzner">
                            <el-form-item style="height: 90%;" v-if="data.release||data.index != 2" prop="textarea">
                                <el-input maxlength="255" style="height: 100%;" v-model="form.textarea" :rows="2"
                                    type="textarea" placeholder="内容，不能少于1，大于255字" />
                            </el-form-item>
                            <el-scrollbar v-else height="100%"> {{ dataList[showIndex]?.content }}</el-scrollbar>
                        </div>
                        <div v-if="data.index == 2&&!release" style="font-size: 0.5vw;">开始时间：{{
                            time(new
                                Date(dataList[showIndex]?.startTime)) }}</div>
                        <el-form-item v-else prop="startTime">
                            <el-date-picker v-model="form.startTime" :default-time="defaultTime" type="datetime"
                                placeholder="通知开始时间" />
                        </el-form-item>
                        <div v-if="data.index == 2&&!release" style="font-size: 0.5vw;">结束时间：{{ time(new Date(form.endTime)) }}
                        </div>
                        <el-form-item v-else prop="endTime">
                            <el-date-picker v-model="form.endTime" :default-time="defaultTime" type="datetime"
                                placeholder="通知结束时间" />
                        </el-form-item>

                    </el-form>
                    <el-select v-if="data.release||index!=2" v-model="operation" class="m-2" 
                        placeholder="发送方式" style="margin-bottom: 1vh; width: 70%;">
                        <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <div class="duix" v-if="index==2&&!data.release||operation=='MORE'">接收对象</div>
                    <!-- 选中的用户 -->
                    <div class="userList" v-if="index==2&&!data.release||operation=='MORE'">
                        <el-scrollbar height="100%">
                            <div class="imgs">
                                <!-- <div v-if="!data.release" v-for="item, index in dataList[showIndex]?.briefUserVos"
                                    :key="item.userId" class="user">
                                    <img :src="item.imageUrl"
                                        @error="item.imageUrl = 'https://finally-oss.oss-cn-hangzhou.aliyuncs.com/user_image/19251104252.jpg'"
                                        alt="">
                                    <div @click="deleteUser(index)" class="span">-</div>
                                    <div class="username">{{ item.userName }}</div>
                                </div> -->
                                <div v-for="item, index in userNotice" :key="item.userId" class="user">
                                    <img :src="item.imageUrl"
                                        @error="item.imageUrl = 'https://finally-oss.oss-cn-hangzhou.aliyuncs.com/user_image/19251104252.jpg'"
                                        alt="">
                                    <div v-if="data.index!=2" @click="deleteUser(index,true)" class="span">-</div>
                                    <div class="username">{{ item.userName }}</div>
                                </div>
                                <div v-if="data.index == 1 || data.release" class="add" @click="dialogVisible = true">
                                    <div class="up">+</div>
                                    <div class="username">编辑</div>
                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                    <div class="button">
                        <el-button v-if="data.release" style="width: 100%;" @click="submitForm(ruleFormRef, pushNotic)"
                            type="primary" round>发送通知</el-button>
                        <el-button style="width: 100%;" @click="pushNotic" v-else-if="data.index == 1"
                            round>修改通知</el-button>
                        <el-button v-else-if="!dataList[showIndex]?.readStatus" style="width: 100%;" @click="pushNotic"
                            type="primary" round>确认收到</el-button>
                        <el-button v-else style="width: 100%;" type="primary" round>已经确认通知</el-button>
                    </div>

                </div>
            </template>
        </el-drawer>

        <!-- 勾选发送通知的人 -->
        <el-dialog v-model="dialogVisible" title="勾选发送通知的人" width="30%">

            <el-scrollbar style="height: 40vh;" height="100%">
                <el-tree :data="datass" ref="treeRef" default-expand-all node-key="id" highlight-current
                    :props="defaultProps">
                    <template #default="{ node, data }">

                        <span class="custom-tree-node">
                            <span>{{ node?.label }}</span>
                            <div v-if="data.userList.length != 0" class="spans" type="text"
                                @click.stop="handleCheckChange(data)">添加</div>
                        </span>
                    </template>
                </el-tree>
            </el-scrollbar>
            <el-scrollbar style="height: 7vh; margin-bottom: 2vh;" height="100%">
                <span v-for="(item, index) in userNotice">{{ item.userName }}<span
                        v-if="index != userNotice.length - 1">、</span></span>
            </el-scrollbar>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="pushUserList">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </teleport>
</template>

<script lang="ts" setup>
import { ref, watch, computed, watchEffect, reactive } from "vue"
import { pageNoticePerson, pageNotice, showUser, sendNotice, acceptNotice, updateNotice, deleteNotice } from '@/request/api'
import { time, useWebSocket } from '@/hooks/index'
import type { List } from '@/type/notice'
import { useStore } from '@/stores/counter'
import { ElNotification, ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
let operation=ref('')
let options=reactive([{
    name:'广播',
    value:"ALL"
},{
    name:'群发',
    value:"MORE"
}])
interface Request {
    /**
     * undefined[ 被通知用户id ]
     */
    acceptIds: string[];
    /**
     * 通知内容
     */
    content: string;
    /**
     * 结束时间
     */
    endTime: Date;
    /**
     * 通知id
     */
    id?: number;
    /**
     * 发送通知的对象
     */
    operation: string;
    /**
     * 开始时间
     */
    startTime: any;
    /**
     * 标题
     */
    title: string;
}
const defaultTime = new Date(2000, 1, 1, 12, 0, 0)
const store = useStore()
const data = defineProps<{
    index: number,      //用于切换通知类型
    release: boolean     //是否发送通知,
    setRelease: Function
}>()



//弹窗,用于选择学生
let dialogVisible = ref(false)
interface userNotice {
    imageUrl: string
    userId: string
    userName: string
}
interface Tree {
    userList: userNotice[],
}
//获取当前用户可以发送通知的人
showUser(store.user.organizationId).then(res => {
    datass.push(res.data)
})
const defaultProps = reactive({
    children: 'children',
    label: 'label',
    disabled: 'disabled',
})
//当复选框被点击时
const handleCheckChange = (
    data: Tree) => {
    if (userNotice.length == 0) {
        userNotice.push(...data.userList)
        return
    }

    let obj: any = {}
    data.userList.forEach((element) => {
        obj[element.userId] = 1
    })
    let ac = userNotice.filter((element) => {
        if (!(element.userId in obj))
            return element
    })

    userNotice.length = 0
    userNotice.push(...ac, ...data.userList)
}
//可以通知的人
const datass: any = reactive([])
//被选中通知的人
const userNotice = reactive<userNotice[]>([])
//关闭弹窗加渲染选择用户
const pushUserList = () => {
    dialogVisible.value = false
}



let loading = ref<boolean>(false)
//分页
let pageIndex = 0
let pageCount = ref<number>(1)            //总页数
//点击分页后
const currentChange = (e: number) => {
    pageIndex = e
    transferStation()
}
//获取数据
let dataList = reactive<List[]>([])
/**
 * 获取我发出去的通知
 */
const requestPageNotice = (pageIndex: number,input:string) => {
    if (loading.value == true) return          //节流阀
    loading.value = true
    pageNotice({ pageIndex, pageSize: 15, content: input }).then(res => {
        dataList.length = 0
        pageCount.value = res.data.pageCount
        dataList.push(...res.data.list)
        loading.value = false

    })
}
/**
 * 获取我收到的通知
 */
const requestpageNoticePerson = (pageIndex: number,input:string) => {
    if (loading.value == true) return          //节流阀
    loading.value = true
    pageNoticePerson({ pageIndex, pageSize: 15, content: input}).then(res => {
        dataList.length = 0
        pageCount.value = res.data.pageCount
        dataList.push(...res.data.list)
        loading.value = false

    })
}
//中转站
const transferStation = (input:string='') => {
    if (data.index == 2) {
        requestpageNoticePerson(pageIndex,input)
    } else
        requestPageNotice(pageIndex,input)
}
let indexs = computed(() => {
    return data.index
})
//进入页面获取数据
transferStation()
//当点击左侧切换通知时
watch(indexs, () => {
    if (data.index && data.index != 3) {
        transferStation()
    }

})

defineExpose({
    transferStation
});
//通知
//打开通知
const drawer2 = ref(false)
const direction = ref('rtl')        //通知出现位置
let showIndex = ref(0)          //用于查看点击了那条通知
const showDrawer = (index: number) => {
    drawer2.value = true
    form.textarea = dataList[index].content
    form.input = dataList[index].title
    form.endTime = dataList[index].endTime
    form.startTime = dataList[index].startTime
    showIndex.value = index,
    operation.value=dataList[index].operation
    userNotice.length=0
    userNotice.push(...dataList[index].briefUserVos)
    submitForm(ruleFormRef.value)
}
const deleteUser = (index: number ,userNotices:boolean=false) => {
    //判断是删除刚添加的还是删除以前就发过的人

    if(userNotices)
    userNotice.splice(index, 1)
    else{
        dataList[showIndex.value].briefUserVos.splice(index, 1)        
    }

}


//表单校验
const form: any = reactive({
    input: '',
    textarea: '',
    endTime: '',
    startTime: ''
})

//校验条件
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
    "input": [
        { min: 1, max: 255, message: '请输入11位手机号', trigger: 'blur' },
        { required: true, message: '请输入1到255个字', trigger: 'blur' },
    ],
    "textarea": [
        { min: 1, max: 255, message: '请输入11位手机号', trigger: 'blur' },
        { required: true, message: '请输入1到255个字', trigger: 'blur' },
    ],
    "endTime": { required: true, message: '时间不能为空', trigger: 'blur' },
    "startTime": { required: true, message: '时间不能为空', trigger: 'blur' }
})
//开始验证表单
const submitForm = async (formEl: FormInstance | undefined, pushNotic: Function | null = null) => {
 

    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            //开始进行登录，服务端验证
            pushNotic && pushNotic()
        } else {
        }
    })
}
//发布通知逻辑
let dataRelease = computed(() => {
    return data.release
})
//当点击创建通知按钮时
watch(dataRelease, (a) => {
    if (a) {

        drawer2.value = true
        form.textarea = ''
        form.input = ''
        form.endTime = ''
        form.startTime = ''
        userNotice.length=0
        showIndex.value=-1
        operation.value=''
    }
})
//调用通知接口后的回调
const showSuccess = (text: string) => {
    userNotice.length = 0
    operation.value='MORE'
    drawer2.value = false
    ElNotification({
        title: '通知操作',
        message: `${text}`,
        type: 'success',
        position: 'top-right',
    })
    transferStation()
}
//对通知进行发布和修改及确认
const pushNotic = () => {

    if (data.index == 1 && !data.release) {
        let notice = [...userNotice]
        //用于存储需要通知的人
        let arr: string[] = []
        notice.forEach(e => {
            arr.push(e.userId)
        })
        updateNotice<Request>({
            id: dataList[showIndex.value].id,
            title: form.input,
            content: form.textarea,
            startTime: form.startTime,
            operation: operation.value,
            acceptIds: arr,
            endTime: new Date(form.endTime)
        }).then(res => {
            return res.data ? Promise.resolve(res.data) : Promise.reject(res.msg)
        }).then((res: string) => {
            dataList[showIndex.value].content = form.textarea,
                dataList[showIndex.value].title = form.input,
                dataList[showIndex.value].briefUserVos.length = 0
            dataList[showIndex.value].briefUserVos = notice
            dataList[showIndex.value].endTime = new Date(form.endTime),
                showSuccess(res)
        }).catch(err => {
            ElMessage.error(err)
        })
    } else if (data.index == 2 && !data.release) {
        acceptNotice<number>(dataList[showIndex.value].id).then(res => {
            showSuccess(res.data)
        })
    } else {
        //用于存储需要通知的人
        let arr: string[] = []
        userNotice.forEach(e => {
            arr.push(e.userId)
        })
        sendNotice<Request>({
            title: form.input,
            content: form.textarea,
            startTime: form.startTime,
            operation: operation.value,
            acceptIds: arr,
            endTime: new Date(form.endTime)
        }).then(res => {
            return res.data ? Promise.resolve(res.data) : Promise.reject(res.msg)

        }).then(res => {
            showSuccess(res)
        }).catch(err => {
            ElMessage.error(err)
        })
    }
 drawer2.value=false
}


const messages = (e: any) => {
    if (e instanceof Array) return
    if (e.type == "NOTICE") {
        transferStation()
    }
}
let ws = useWebSocket('notice', messages)

//删除通知
const deletes = (id: number) => {
    deleteNotice(id).then(res => {
        showSuccess(res.data)
    })
}
</script>

<style lang=less  scoped>
.delete {
    display: none;
}

.rigth {
    width: calc(75% - 1px);
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    background-color: @backColor;
    color: @color;
    .pagin {
        height: 50px;
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;
    }

    .container {
        display: flex;

        cursor: pointer;
        margin: 0px 2vw;

        border-radius: 1vw;
        padding: 2vh 1vw 0px 1vw;

        .text {

            flex: 1;
            font-size: 0.8vw;
            padding-bottom: 1vh;
            border-bottom: 1px solid #F0F2F5;

            >div:nth-child(2) {
                color: #A2A3A5;
                font-size: 0.5vw;
                .texttwo();
                margin-top: 1vh;

            }
        }

        .function {
            width: 10%;
            height: 100%;
            font-size: 0.5vw;
            color: #A2A3A5;
            margin-left: 1vw;
            .textNOLine();
            text-align: right;
        }

        .ico {
            margin-right: 1vw;
            background-color: #4272D3;
            padding: 0.5vh;
            color: #fff;
            font-size: 0.7vw;
            border-radius: 0.5vh;

        }
    }

    .container:hover {
        background-color: #F6F6F6;
    }

    .container:hover .delete {
        display: block;
    }

    .container:hover .time {
        display: none;
    }
}

.drawerContainer {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .button {
        width: 100%;
    }

    .image {
        width: 50px;
        aspect-ratio: 1/1;
        border-radius: 50%;
        margin-right: 1vw;
    }

    .users {
        background-color: #FFFFFF;
        width: 100%;
        height: 70px;
        padding-bottom: 1vh;
        border-bottom: 1px solid rgb(219, 219, 219);
        .flexAc();
        margin-bottom: 1vh;

    }

    .bor {
        width: 40px;
        aspect-ratio: 1/1;
        border-radius: 50%;
    }

    .userList {
        background-color: #FFFFFF;
        height: 30%;
        font-size: 0.7vw;

        .imgs {
            flex-wrap: wrap;
            .flexAc();
            position: relative;

            .user {
                .flexSa();
                flex-wrap: wrap;
                width: 76px;
                position: relative;

                .span {
                    .bor();
                    opacity: 0;
                    text-align: center;
                    top: 0px;
                    color: rgb(201, 201, 201);
                    background-color: #8b8b8bb7;
                    cursor: pointer;
                    line-height: 40px;
                    font-size: 40px;
                    position: absolute;
                    transition: all 0.5s;
                }
            }

            .user:hover>.span {
                opacity: 1;
            }

            .username {
                width: 100%;
                .textNOLine();
                text-align: center;
            }

            >div {
                margin: 1vw;
            }

            .add {
                cursor: pointer;
                width: 76px;
                display: flex;
                flex-wrap: wrap;
                justify-content: center;

                .up {
                    color: rgb(146, 144, 144);
                    .username();
                    line-height: 40px;
                    font-size: 30px;
                    border: 1px solid rgb(180, 180, 180);
                    .bor();
                }

            }
        }



        img {
            .bor();
        }

    }

    .duix {
        margin-top: 1vh;
        border-top: 1px solid #DEDEDE;
        font-size: .7vw;
    }

    .tzner {
        overflow: hidden;
        width: 100%;
        background-color: #FFFFFF;
        flex: 1;
        font-size: 1vw;
        margin-bottom: 3vh;
        color: rgb(87, 86, 86);
    }

    :deep(.el-scrollbar__view) {
        width: 100%;
        position: relative;
        word-wrap: break-word;
        word-break: break-all;
        overflow: hidden;
    }

    :deep(.el-textarea__inner) {
        height: 100%;
    }

    :deep(.el-textarea__inner) {
        resize: none;
    }

}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    .spans {
        margin: 0px 3px;
        color: #409EFF;
    }

    .spans::after {
        content: ' ';
        display: block;
        height: 1px;
        background-color: #409EFF;
        transition: all 0.3s ease-in-out;
        transform: scale(0);
        transform-origin: left;

    }

    .spans:hover::after {
        transform: scale(1);
    }
}
</style>